"""
资产与IP综合管理系统 - 主程序入口
ITTS (IT Asset & IP Total Management System)
"""

import sys
import os
import logging
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
if str(project_root) not in sys.path:
    sys.path.insert(0, str(project_root))

from src.app.database import get_database_manager
from src.app.database.init_data import initialize_all_data as init_data
from src.app.ui.main_window import MainWindow
from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('itts.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)

def setup_application():
    """设置应用程序"""
    # 设置高DPI支持 - 必须在QApplication创建之前设置
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    
    app = QApplication(sys.argv)
    
    # 设置应用程序信息
    app.setApplicationName("资产与IP综合管理系统")
    app.setApplicationVersion("1.1")
    app.setOrganizationName("ITTS")
    
    # 设置默认字体
    font = QFont("Microsoft YaHei", 9)
    app.setFont(font)
    
    return app

def initialize_database():
    """初始化数据库"""
    try:
        logger.info("正在初始化数据库...")
        
        # 获取数据库管理器
        db_manager = get_database_manager()
        
        # 检查数据库连接
        if not db_manager.check_connection():
            logger.error("数据库连接失败")
            return None, False
        
        # 创建数据表
        db_manager.create_tables()
        logger.info("数据表创建成功")
        
        # 初始化数据
        with db_manager.get_session() as session:
            init_data(session)
        logger.info("数据初始化成功")
        
        # 显示数据库信息
        db_info = db_manager.get_database_info()
        logger.info(f"数据库信息: {db_info}")
        
        return db_manager, True
        
    except Exception as e:
        logger.error(f"数据库初始化失败: {e}")
        return None, False

def main():
    """主函数"""
    try:
        logger.info("启动资产与IP综合管理系统...")
        
        # 初始化数据库
        db_manager, db_success = initialize_database()
        if not db_success:
            logger.error("数据库初始化失败，系统无法启动")
            return False
        
        # 创建应用程序
        app = setup_application()
        
        # 创建主窗口
        main_window = MainWindow()
        
        # 设置数据库状态
        if hasattr(main_window, 'db_status_label'):
            main_window.db_status_label.setText("🗄️ 数据库：已连接")
        
        # 显示主窗口
        main_window.show()
        
        logger.info("GUI界面启动成功")
        
        # 运行应用程序
        return app.exec_()
        
    except Exception as e:
        logger.error(f"系统启动失败: {e}")
        
        # 显示错误对话框
        try:
            error_app = QApplication.instance()
            if error_app is None:
                error_app = QApplication(sys.argv)
            
            msg_box = QMessageBox()
            msg_box.setIcon(QMessageBox.Critical)
            msg_box.setWindowTitle("启动错误")
            msg_box.setText("系统启动失败")
            msg_box.setInformativeText(f"错误信息：{str(e)}")
            msg_box.setStandardButtons(QMessageBox.Ok)
            msg_box.exec_()
        except:
            print(f"系统启动失败: {e}")
        
        return False
    finally:
        # 关闭数据库连接
        if 'db_manager' in locals() and db_manager:
            db_manager.close_connection()

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)